//
//  WhiteListViewController.m
//  IntelligentHousehold
//
//  Created by wmwMAC on 17/6/26.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "WhiteListViewController.h"

#import "TFAndBtnTableViewCell.h"

#import "AddPopView.h"

#import "WhiteListModle.h"
#import <MessageUI/MessageUI.h>//系统短信


static NSString *identifier = @"TFAndBtnTableViewCell";
@interface WhiteListViewController ()<UITableViewDelegate,UITableViewDataSource,AddPopViewDelegate,TFAndBtnTableViewCellDelegate,MFMessageComposeViewControllerDelegate>
{
    NSArray *HeadTitleArr;
    NSArray *headImgArr;
    
    BOOL allEditMark;
    
    NSString *ChangeTypes;//0代表添加 1代表修改 2代表删除
    
    NSString *msgTitle;//发送短信内容
    NSString *newTelStr;//添加的手机号
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArr;//成员信息
@property (nonatomic,strong)NSMutableDictionary *MagagerDic;//管理员信息
@property (nonatomic, strong) UIButton *editBtn;
@property (nonatomic, strong)NSMutableArray *indextArr;//存储删除内容

@property (strong, nonatomic) UIView *editingView;
@property (strong, nonatomic) UIView *footAddView;
@property (strong, nonatomic) UIButton *allButton;

@property (strong, nonatomic) NSDictionary *saveDic;
//@property (strong, nonatomic) NSString *listType;//0最高权限 1管理员 2成员


@property (strong, nonatomic) UIBarButtonItem *searchItem;
@property (strong, nonatomic) UIButton *addbtn;
@end

@implementation WhiteListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"白名单";
    
   
    self.saveDic = [SaveDataMethord readLoginData];
    
    HeadTitleArr = @[@"管理员号码:",@"成员号码:"];
    headImgArr = @[@"glyhm",@"cyhm"];
    
    
    
    
    self.dataArr = [NSMutableArray array];
    self.indextArr = [NSMutableArray array];
    allEditMark = 0;
    
    
    [self addTableviewUI];
    [self GetQueryWhiteList];
    [self addFootBtnUI];
    
    [self addNavUI];
}

-(void)addNavUI{
    
    if ([[_saveDic objectForKey:@"type"] integerValue] == 0){//管理员

        _searchItem = [[UIBarButtonItem alloc] initWithTitle:@"查询" style:UIBarButtonItemStyleDone target:self action:@selector(searchAction)];
        _searchItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = _searchItem;
    }else{
        
        self.navigationItem.rightBarButtonItem  = nil;
    }
    
}
-(void)searchAction{
//    msgTitle = @"queryphone";
//    [self sendMsg];
    
    
    [self GetQueryWhiteList];
}

-(void)addFootBtnUI{
    _footAddView = [[UIView alloc] initWithFrame:CGRectMake(0, kUIScreenHeight-kNavigationBarHeight-50, kUIScreenWidth, 50)];
    _footAddView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:_footAddView];
    
    if ([[_saveDic objectForKey:@"type"] integerValue] == 0) {//管理员 或者 无数据的第三者
        
         _addbtn = [MyUtil createBtnFrame:CGRectMake(kUIScreenWidth/3, 0, kUIScreenWidth/3, CGRectGetHeight(_footAddView.frame)) title:@" 添加成员" bgImage:nil selectBgImage:nil image:@"tjcy" target:self action:@selector(addBtnAction)];
        [_addbtn setTitleColor:RGBColor(106, 9, 189) forState:UIControlStateNormal];
        [_addbtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        
        [_footAddView addSubview:_addbtn];
    }else{
        _addbtn = nil;
    }
    
    
    
    
}
- (void )editingViewUI{
    
    _editingView = [[UIView alloc] initWithFrame:CGRectMake(0, kUIScreenHeight-kNavigationBarHeight-50, kUIScreenWidth, 50)];
    [self.view addSubview:_editingView];
    
    UIButton *deletButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deletButton.frame = CGRectMake(kUIScreenWidth-80, 0, 80, CGRectGetHeight(_editingView.frame));
    deletButton.backgroundColor = [UIColor redColor];
    [deletButton setTitle:@"删除" forState:UIControlStateNormal];
    [deletButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [deletButton addTarget:self action:@selector(p__buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_editingView addSubview:deletButton];
    
    
    UIView *allView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth-80, CGRectGetHeight(_editingView.frame))];
    [allView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allButtonClick:)]];
    [_editingView addSubview:allView];
    
     _allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _allButton.frame = CGRectMake(10, 0, 80,  CGRectGetHeight(_editingView.frame));
//    allButton.backgroundColor = [UIColor darkGrayColor];
    [_allButton setTitle:@" 全选" forState:UIControlStateNormal];
    [_allButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_allButton setImage:[UIImage imageNamed:@"选择"] forState:UIControlStateNormal];
    _allButton.userInteractionEnabled = NO;
    [allView addSubview:_allButton];
    
    
}
- (void)allButtonClick:(UITapGestureRecognizer *)tap {
    
    allEditMark = !allEditMark;
    if (allEditMark) {
        [self.dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:1] animated:NO scrollPosition:UITableViewScrollPositionNone];
        }];
        [_allButton setImage:[UIImage imageNamed:@"选择1"] forState:UIControlStateNormal];
        
        
    }else{
        
        [[self.tableView indexPathsForSelectedRows] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.tableView deselectRowAtIndexPath:obj animated:NO];
        }];
        [_allButton setImage:[UIImage imageNamed:@"选择"] forState:UIControlStateNormal];
    }
    
    
    
    
    
    
}
-(void)p__buttonClick:(UIButton *)sender{
    
    
    NSLog(@"删除操作");
    ChangeTypes = @"2";
    [self EditWhiteList:_indextArr TelStr:@""];
 
    
}
-(void)addBtnAction{
    NSLog(@"addBtnAction");
    
    if (self.dataArr.count < 9) {
        
        AddPopView *addPopV = [[AddPopView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight)];
//        addPopV.type = @"add";
//        addPopV.type = 1;
        addPopV.delegate = self;
        addPopV.dataArr = self.dataArr.mutableCopy;
        [self.view.window addSubview:addPopV];
    }else{
        [MBProgressHUD showText:@"成员号码数量已达上限!"];
    }
    
    
}
-(void)addPopViewPassTel:(NSString *)telStr TelId:(NSString *)telId{
    // 调用添加修改接口
    ChangeTypes = @"0";
    
    NSInteger numberTag = self.dataArr.count;
    msgTitle = [NSString stringWithFormat:@"setphone:%ld,%@",numberTag+2,telStr];
    newTelStr = telStr;
    
    [self sendMsg];
    
    
}


- (void)addTableviewUI {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight-80) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"TFAndBtnTableViewCell" bundle:nil] forCellReuseIdentifier:identifier];
    //    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier]
    [self.view addSubview:self.tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        if (section == 0) {
            return 1;
        }else{
            return _dataArr.count;
        }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 2;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TFAndBtnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    cell.delegate = self;
    cell.dataArr = self.dataArr;
    
    NSString *typeStr = [self.saveDic objectForKey:@"type"];
    cell.ManagerTypeStr = typeStr.integerValue;//成员
    
    
    
        if (indexPath.section == 0) {
            cell.rightBtn.hidden = NO;
            
            cell.managerDic = self.MagagerDic;
            cell.type = 0;
            
            NSString *managerTelStr = self.MagagerDic[@"wtell"];
            
            
            
            
            if (!managerTelStr.length) {
                cell.textLabel.text = @"";
                [cell.rightBtn setTitle:@"设置" forState:UIControlStateNormal];
            }else{
                
                if ([[_saveDic objectForKey:@"type"] integerValue] == 1) {//成员
                    managerTelStr = [managerTelStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
                }else if ([[_saveDic objectForKey:@"type"] integerValue] == 2){//或第三者
                    managerTelStr = @"";
                }
                cell.textLable.text = managerTelStr;
                cell.textLable.font = [UIFont systemFontOfSize:16];
                [cell.rightBtn setTitle:@"更新" forState:UIControlStateNormal];
                
                
            }
            
            
        }else{
            WhiteListModle *modle = self.dataArr[indexPath.row];
            //        cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.tag = indexPath.row +2000;
            cell.textLable.text = modle.wtell;
            cell.modle = modle;
            
            
            cell.type = 1;
            
            if ([[_saveDic objectForKey:@"type"] integerValue] == 1) {//成员
                cell.rightBtn.hidden = YES;
            }else{
                cell.rightBtn.hidden = NO;
            }
            
        }
//    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 70;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 10)];
    lineView.backgroundColor = BaseColor;
    [headerView addSubview:lineView];
    
    UIImageView *imgView = [MyUtil createImageViewFrame:CGRectMake(10, 40, 15, 15) imageName:[NSString stringWithFormat:@"%@",headImgArr[section]]];
    [headerView addSubview:imgView];
    
    UILabel *headLable = [MyUtil createLabelFrame:CGRectMake(CGRectGetMaxX(imgView.frame)+10, CGRectGetMinY(imgView.frame), kUIScreenWidth/2, 20) title:HeadTitleArr[section] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentLeft font:[UIFont systemFontOfSize:14]];
    [headerView addSubview:headLable];
    
//    if (section == 1 && self.listType.integerValue == 0) {
    
//        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        _editBtn.frame = CGRectMake(kUIScreenWidth-60, CGRectGetMinY(imgView.frame), 50, 20);
//        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
//        [_editBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [_editBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
//        [_editBtn addTarget:self action:@selector(editBtnAction) forControlEvents:UIControlEventTouchUpInside];
//        [headerView addSubview:_editBtn];
//        
//        UIBarButtonItem *editBtnItem = [[UIBarButtonItem alloc] initWithCustomView:_editBtn];
//        
//        editBtnItem = self.editButtonItem;
    
//    }
    
    return headerView;
}
-(void)editBtnAction{
    //支持同时选中多行
    
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    
    self.tableView.editing = !self.tableView.editing;
    
    if (self.tableView.editing) {
        
        //        _editBtn.hidden = NO;
        
        [_editBtn setTitle:@"取消" forState:UIControlStateNormal];
         [self editingViewUI];
        [_footAddView removeFromSuperview];
        
    }else{
        
        //        _editBtn.hidden = YES;
        
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [self addFootBtnUI];
        [_editingView removeFromSuperview];
    }
    NSLog(@"editBtnAction");
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 30;
    }else{
        return 100;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    footview.backgroundColor = [UIColor whiteColor];
    
    
    return footview;
}



// 批量删除
// 1. 开启
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
    // 点击done时删除(为NO)(此时editing = 0)
    if (!editing) {
        //删除数据
        // 空数组 保存要删除的对象
        NSMutableArray *arr = [NSMutableArray array];
        // 遍历下标 获取对象
        for (NSIndexPath *i in _indextArr) {
            [arr addObject:_dataArr[i.row]];
        }
        // 删除数据
        [_dataArr removeObjectsInArray:arr];
        // 删除视图
        [_tableView deleteRowsAtIndexPaths:_indextArr withRowAnimation:(UITableViewRowAnimationRight)];
        // 清空数组
        [_indextArr removeAllObjects];
    }
    // 写在外边就不用if (tableView.editing)判断了
    //    [_indextArr removeAllObjects];
}
// 2.设置多选
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    
}
//3.(多选时)触发select方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"选中");
    if (tableView.editing) {
        WhiteListModle *modle = self.dataArr[indexPath.row];
        
        // 保存选中index
        [_indextArr addObject:modle.iid];
    }else{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}
// 设置是否可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    } else {
        return YES;
    }
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"取消选中");
    if (tableView.editing) {
        //取消选中时 移除坐标
        WhiteListModle *modle = self.dataArr[indexPath.row];
        
        // 保存选中index
        [_indextArr addObject:modle.iid];
        
        NSLog(@"%@",_indextArr);
    }
}

// 左滑删除
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    //delete
    UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDefault) title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 删除操作
        [_dataArr removeObjectAtIndex:indexPath.row];
        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationMiddle)];
    }];
    //mark
    UITableViewRowAction *mark = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleNormal) title:@"标记未读" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"哒哒哒");
    }];
    return @[delete, mark];
    
}
//获取白名单列表
-(void)GetQueryWhiteList{
    
    self.saveDic = [SaveDataMethord readLoginData];
    
    NSString *url = [NSString stringWithFormat:QUERYWHITELIST,RealmName];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:_saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:_saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:_saveDic[@"locknumber"] forKey:@"locknumber"];
    [parameDic setObject:_saveDic[@"tell"] forKey:@"tell"];
    [parameDic setObject:self.saveDic[@"type"] forKey:@"type"];
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
        self.dataArr = [WhiteListModle mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@ "data"]];
        
        NSArray *adMinArr = [responseObject objectForKey:@"admin"];
        NSDictionary *adMinDic = adMinArr.firstObject;
        if (adMinDic.count) {
             self.MagagerDic = [NSDictionary dictionaryWithDictionary:adMinDic].mutableCopy;
        }
        
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    ///13750891239
}
// 编辑白名单
-(void)EditWhiteList:(NSArray *)deletArr TelStr:(NSString *)telStr{
    
    
    NSString *url = [NSString stringWithFormat:EDITWHITE,RealmName];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:_saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:_saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:[NSString stringWithFormat:@"%@",ChangeTypes] forKey:@"types"];//0代表添加 1代表修改 2代表删除
    [parameDic setObject:_saveDic[@"locknumber"] forKey:@"locknumber"];
    
    
    [parameDic setObject:@"1" forKey:@"type"];//0代表管理员 1代表成员
    
    if (ChangeTypes.integerValue == 2) {
        NSString *deletStr = [BasePublicClass returnStringFromDicOrArray:deletArr];
        [parameDic setObject:deletStr forKey:@"id"];//修改删除需要这个代表白名单成员对应id
        

    }else if (ChangeTypes.integerValue == 0){//添加
        [parameDic setObject:@"" forKey:@"id"];
        [parameDic setObject:telStr forKey:@"wtell"];
    }
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        
        if ([[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
            
            [self GetQueryWhiteList];
            [MBProgressHUD showText:@"成功"];
            
        }else{
            
            [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"msg"]]];
        }
        
        NSLog(@"%@",responseObject);
    } failure:^(NSError *error) {
        
    }];

}
-(void)TFAndBtnTableViewCellPaddReloadDate:(NSString *)tfString{
    [self GetQueryWhiteList];
    [self addNavUI];
    [self addFootBtnUI];
}



#pragma mark -------------- 发送短信 ----------------
-(void)sendMsg{
    NSString *telStr = _saveDic[@"locknumber"];
//    telStr = @"10086";
    
    // 判断是否已经存在该成员号码
//    BOOL canAdd = YES;
//    for (WhiteListModle *modle in self.dataArr) {
//        if ([modle.wtell isEqualToString:newTelStr]) {
//            canAdd = NO;
//        }
//    }
//    if (canAdd) {
        [self showMessageView:[NSArray arrayWithObjects:telStr, nil] title:nil body:msgTitle];
//    }else{
//        [MBProgressHUD showText:@"已有此成员号码"];
//    }


    
    
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if( [MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该设备不支持短信功能 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - MFMessageComposeViewController

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (result) {
        if (MessageComposeResultSent) {//短信发送成功
            
            if ([msgTitle isEqualToString:@"queryphone"]) {
                [self GetQueryWhiteList];
            }else{
                [self EditWhiteList:nil TelStr:newTelStr];
            }
            
            
        }
    }
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
